from kubernetes import client, config
from os import path
import yaml

class k8sapi:
    def k8s_conn(self):
        config.kube_config.load_kube_config(config_file="kubeconfig.yaml")
        conn = client.CoreV1Api()
        return conn

    def namespaces(self):
        # 列出 namespaces
        conn = self.k8s_conn()
        ret = conn.list_pod_for_all_namespaces(watch=False)
        for i in ret.items:
            print("%s   %s      %s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

    def services(self):
        # 列出所有的services
        conn = self.k8s_conn()
        ret = conn.list_service_for_all_namespaces(watch=False)
        for i in ret.items:
            print("%s   %s      %s      %s      %s " % (i.kind, i.metadata.namespace, i.metadata.name, i.spec.cluster_ip, i.spec.ports))

    def pods(self):
        # 列出所有的pod
        conn = self.k8s_conn()
        ret = conn.list_pod_for_all_namespaces(watch=False)
        for i in ret.items:
            print("%s   %s      %s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

    def create(self):
        config.load_kube_config()
        with open(path.join(path.dirname(__file__), "/root/deploy.yaml")) as f:
            dep = yaml.safe_load(f)
            k8s_apps_v1 = client.AppsV1Api()
            resp = k8s_apps_v1.create_namespaced_deployment(
                body=dep, namespace="default")
            print("Deployment created. status='%s'" % resp.metadata.name)
    def delete(self):
        config.load_kube_config()
        k8s_core_v1 = client.CoreV1Api()
        resp = k8s_core_v1.delete_namespaced_pod(namespace="default", name='nginx-pod')
        print("delete Pod ")


if __name__ == '__main__':
    myk8s = k8sapi()
    myk8s.pods()
    myk8s.namespaces()
    myk8s.services()